#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
为markdown文件生成简洁目录的脚本（无锚点、无列表符号）
"""

import os
import re

def extract_h2_titles(content):
    """提取所有二级标题并去除前缀数字和符号"""
    pattern = r'^##\s+(.+)$'
    matches = re.findall(pattern, content, re.MULTILINE)
    # 移除标题中的前缀数字、符号和空格
    cleaned_titles = []
    for title in matches:
        # 匹配并移除前缀数字、中文数字、符号和空格
        cleaned = re.sub(r'^[\d一二三四五六七八九十]+[\.、\s]*', '', title)
        cleaned_titles.append(cleaned)
    return cleaned_titles

def has_toc(content):
    """检查是否已经存在目录"""
    toc_indicators = [
        '## 目录',
        '## 📋 目录',
        '## Table of Contents',
        '## TOC',
        '## 内容导航'
    ]
    for indicator in toc_indicators:
        if indicator in content:
            return True
    return False

def remove_existing_toc(content):
    """移除现有的目录"""
    # 匹配目录开始到下一个二级标题或三级标题之间的内容
    toc_pattern = r'^##\s+(目录|📋 目录|Table of Contents|TOC|内容导航)\s*\n(.*?)(?=\n##\s+|\n###|\n#\s|\n\n##|\n\n###|\Z)'
    
    # 先尝试完整匹配
    new_content = re.sub(toc_pattern, '', content, flags=re.MULTILINE | re.DOTALL)
    
    # 如果还有残留的目录标记，进一步清理
    lines = new_content.split('\n')
    cleaned_lines = []
    skip_mode = False
    
    for line in lines:
        if line.strip() == '## 目录' or line.strip() == '## 📋 目录':
            skip_mode = True
            continue
        elif skip_mode and (line.startswith('## ') or line.startswith('# ') or line.startswith('### ')):
            skip_mode = False
            
        if not skip_mode:
            cleaned_lines.append(line)
    
    return '\n'.join(cleaned_lines)

def add_simple_toc_to_file(file_path):
    """为单个文件添加简洁目录"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read()
        
        # 先移除现有目录
        content = remove_existing_toc(content)
        
        # 提取二级标题
        h2_titles = extract_h2_titles(content)
        if len(h2_titles) < 2:
            print(f"跳过: {os.path.basename(file_path)} - 二级标题不足")
            return False
        
        # 创建简洁目录内容（无锚点、无列表符号）
        toc_lines = ['## 目录', '']
        for i, title in enumerate(h2_titles, 1):
            toc_lines.append(f'{i}. {title}')
        toc_lines.extend(['', '---', ''])
        
        # 找到一级标题后的位置插入目录
        lines = content.split('\n')
        insert_index = 0
        for i, line in enumerate(lines):
            if line.startswith('# ') and not line.startswith('##'):
                insert_index = i + 1
                break
        
        # 插入目录
        new_lines = lines[:insert_index] + toc_lines + lines[insert_index:]
        new_content = '\n'.join(new_lines)
        
        # 写回文件
        with open(file_path, 'w', encoding='utf-8') as f:
            f.write(new_content)
        
        print(f"成功: {os.path.basename(file_path)} - 更新为简洁目录")
        return True
        
    except Exception as e:
        print(f"错误: {os.path.basename(file_path)} - {str(e)}")
        return False

def main():
    # 项目根目录
    root_dir = r"e:\BaiduSyncdisk\Android系统开发之路"
    
    # 查找所有markdown文件
    md_files = []
    for root, dirs, files in os.walk(root_dir):
        for file in files:
            if file.endswith('.md'):
                md_files.append(os.path.join(root, file))
    
    print(f"找到 {len(md_files)} 个markdown文件")
    print("=" * 50)
    
    # 处理每个文件
    success_count = 0
    for file_path in md_files:
        if add_simple_toc_to_file(file_path):
            success_count += 1
    
    print("=" * 50)
    print(f"处理完成: 成功更新 {success_count} 个文件的目录格式")

if __name__ == "__main__":
    main()